import React, { useState, useEffect } from 'react'
import PubSub from 'pubsub-js'
import Header from './components/Header/Header'
import List from './components/List/List'
import Footer from './components/Footer/Footer'
import Item from './components/Item/Item'
import './App.css'
export default function App() {
  const [list, setList] = useState([
    {
      id: 1,
      todoName: '喝水',
      isDone: false,
    },
    {
      id: 2,
      todoName: '喝茶',
      isDone: true,
    },
  ])

  useEffect(() => {
    // 挂载订阅
    const addToken = PubSub.subscribe('add', (topic, todoName) => {
      //生成任务对象
      const todo = {
        id: Date.now(),
        todoName,
        isDone: false,
      }
      // const newList = [...list]

      // setList(newList)
      setList((list) => {
        // list就是setList所对应的数据最新值
        const newList = [...list]
        newList.push(todo)
        // setList参数如果写成回调函数,回调中必须写return. return的值就是要修改的目标值
        return newList
      })
    })
    return () => {
      //卸载取消订阅
      PubSub.unsubscribe(addToken)
    }
  }, [])
  return (
    <div className="todo-container">
      <div className="todo-wrap">
        <Header></Header>
        <div>
          <List>
            {list.map((item) => (
              <Item key={item.id} todo={item}></Item>
            ))}
          </List>
          <Footer></Footer>
        </div>
      </div>
    </div>
  )
}
